package com.example.myproject;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

public class JPAUtil {

	public static void updateObject(Object obj){
		EntityManager em = EMF.getEM();
		EntityTransaction trans = em.getTransaction();
		try {
		    trans.begin();
		    em.merge(obj);
		}catch(Exception e){
		    e.printStackTrace();
		}finally {
		    trans.commit();
		}
	}
	
	public static void persistObject(Object obj){
		EntityManager em = EMF.getEM();
		EntityTransaction trans = em.getTransaction();
		try {
		    trans.begin();
		    em.persist(obj);
		}catch(Exception e){
		    e.printStackTrace();
		}finally {
		    trans.commit();
		}
	}
	
	public static List findByProperty(String className, String propertyName, Object value){
		EntityManager em = EMF.getEM();
		String sql = "select from " + className + " c where c." + propertyName + "=:value";
		System.out.println(propertyName + ":" + value);
		List ts = null;
		try{
			ts = em.createQuery(sql)
			.setParameter("value", value).getResultList();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ts;
	}

	@SuppressWarnings("unchecked")
	public static Object findById(Class persistClass,Long id) {
		EntityManager em = EMF.getEM();
		Object t = null;
		try {
			System.out.println("id:"+id);
			t = em.find(persistClass, id);
		}catch(Exception e){
			e.printStackTrace();
		}
		return t;
	}
	
	@SuppressWarnings("unchecked")
	public static List list(Class persistClass){
		EntityManager em = EMF.getEM();
		String sql = "select c from " + persistClass.getName() + " c";
		List ts = null;
		try{
			ts = em.createQuery(sql).getResultList();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ts;
	}
	
}
